package com.yanxinim.cn.store;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanxinim.cn.AppConfig;
import com.yanxinim.cn.R;
import com.yanxinim.cn.helper.AvatarHelper;
import com.yanxinim.cn.store.bean.AuthUserInfo;
import com.yanxinim.cn.ui.base.BaseActivity;
import com.yanxinim.cn.util.BitmapUtil;
import com.yanxinim.cn.util.CameraUtil;
import com.yanxinim.cn.util.HttpUtils;
import com.yanxinim.cn.util.JsonTool;
import com.yanxinim.cn.util.ToastUtil;
import com.yanxinim.cn.util.picker.ImagePickerHelper;
import com.yanxinim.cn.view.MergerStatus;
import com.yanxinim.cn.view.SkinImageView;
import com.yanxinim.cn.view.SkinTextView;
import com.ypx.imagepicker.bean.ImageItem;
import com.ypx.imagepicker.bean.PickerError;
import com.ypx.imagepicker.data.OnImagePickCompleteListener2;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AuthUserInfoActivity extends BaseActivity {
    //    @BindView(R.id.iv_store_icon)
//    ImageView ivStoreIcon;
    @BindView(R.id.iv_title_left)
    SkinImageView ivTitleLeft;
    @BindView(R.id.tv_title_left)
    SkinTextView tvTitleLeft;
    @BindView(R.id.pb_title_center)
    ProgressBar pbTitleCenter;
    @BindView(R.id.tv_title_center)
    SkinTextView tvTitleCenter;
    @BindView(R.id.iv_title_center)
    ImageView ivTitleCenter;
    @BindView(R.id.iv_title_right)
    SkinImageView ivTitleRight;
    @BindView(R.id.iv_title_right_right)
    SkinImageView ivTitleRightRight;
    @BindView(R.id.tv_title_right)
    SkinTextView tvTitleRight;
    @BindView(R.id.mergerStatus)
    MergerStatus mergerStatus;
    @BindView(R.id.iv_card_up)
    ImageView ivCardUp;
    @BindView(R.id.iv_card_down)
    ImageView ivCardDown;
    private static final int REQUEST_CODE_CAPTURE_CROP_PHOTO = 1;
    private static final int REQUEST_CODE_PICK_CROP_PHOTO = 2;
    private static final int REQUEST_CODE_CROP_PHOTO = 3;
    private static final int REQUEST_CODE_SET_ACCOUNT = 5;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.ll_create_user)
    LinearLayout llCreateUser;
    @BindView(R.id.tv_real_name)
    TextView tvRealName;
    @BindView(R.id.tv_user_sex)
    TextView tvUserSex;
    @BindView(R.id.tv_user_idcard)
    TextView tvUserIdcard;
    @BindView(R.id.ll_user_info)
    LinearLayout llUserInfo;
    @BindView(R.id.iv_card_up2)
    ImageView ivCardUp2;
    @BindView(R.id.rl_card_up)
    RelativeLayout rlCardUp;
    @BindView(R.id.iv_card_down2)
    ImageView ivCardDown2;
    @BindView(R.id.rl_card_down)
    RelativeLayout rlCardDown;
    //    private File mCurrentFile;
    int type;//1-正面， 2-反面
    boolean isUp;
    boolean isDown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth_user_info);
        ButterKnife.bind(this);
        tvTitleCenter.setText("实名认证");

    }

    @OnClick({R.id.iv_title_left, R.id.rl_card_up, R.id.rl_card_down, R.id.tv_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.rl_card_up:
                type = 1;
                showSelectAvatarDialog();
                break;
            case R.id.rl_card_down:
                type = 2;
                showSelectAvatarDialog();
                break;
            case R.id.tv_commit:
                if (!isUp) {
                    ToastUtil.showToast(AuthUserInfoActivity.this, "请上传身份证正面");
                    return;
                }
                if (!isDown) {
                    ToastUtil.showToast(AuthUserInfoActivity.this, "请上传身份证反面");
                    return;
                }
                commitImage();
                break;
        }
    }

    private void showSelectAvatarDialog() {
        ImagePickerHelper.pickSingleImageCrop(this, new OnImagePickCompleteListener2() {
            @Override
            public void onPickFailed(PickerError error) {
                ToastUtil.showToast(mContext, R.string.c_photo_album_failed);
            }

            @Override
            public void onImagePickComplete(ArrayList<ImageItem> items) {
                String data = items.get(0).getCropUrl();
                mNewPhotoUri = Uri.parse(data);
                if (type == 1) {
                    AvatarHelper.getInstance().displayUrl(mNewPhotoUri.toString(), ivCardUp);
                    ivCardUp2.setVisibility(View.GONE);
                    bitmap = BitmapUtil.decodeBitmapFromFile(data, 316, 200);
                    isUp = true;
                } else if (type == 2) {
                    AvatarHelper.getInstance().displayUrl(mNewPhotoUri.toString(), ivCardDown);
                    ivCardDown2.setVisibility(View.GONE);
                    isDown = true;
                }
            }
        });


//        String[] items = new String[]{getString(R.string.photograph), getString(R.string.album)};
//        AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(getString(R.string.select_avatars))
//                .setSingleChoiceItems(items, 0,
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                if (which == 0) {
//                                    takePhoto();
//                                } else {
//                                    selectPhoto();
//                                }
//                                dialog.dismiss();
//                            }
//                        });
//        builder.show();
    }

    private Uri mNewPhotoUri;
    Bitmap bitmap;

    private void takePhoto() {
        mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
        CameraUtil.captureImage(this, mNewPhotoUri, REQUEST_CODE_CAPTURE_CROP_PHOTO);
    }

    private void selectPhoto() {
        CameraUtil.pickImageSimple(this, REQUEST_CODE_PICK_CROP_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAPTURE_CROP_PHOTO) {// 拍照返回再去裁减
            if (resultCode == Activity.RESULT_OK) {
                if (mNewPhotoUri != null) {
                    Uri o = mNewPhotoUri;
                    mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
//                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    CameraUtil.cropImage(this, o, mNewPhotoUri, REQUEST_CODE_CROP_PHOTO, 3, 2, 300, 200);
                } else {
                    ToastUtil.showToast(this, R.string.c_photo_album_failed);
                }
            }
        } else if (requestCode == REQUEST_CODE_PICK_CROP_PHOTO) {// 选择一张图片,然后立即调用裁减
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
//                    Uri o = Uri.fromFile(new File(CameraUtil.parsePickImageResult(data)));
                    Uri o = CameraUtil.getUriFromFile(mContext, CameraUtil.parsePickImageResult(data));

                    mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
//                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    CameraUtil.cropImage(this, o, mNewPhotoUri, REQUEST_CODE_CROP_PHOTO, 3, 2, 300, 200);
                } else {
                    ToastUtil.showToast(this, R.string.c_photo_album_failed);
                }
            }
        } else if (requestCode == REQUEST_CODE_CROP_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
                if (mNewPhotoUri != null) {
//                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    if (type == 1) {
                        AvatarHelper.getInstance().displayUrl(mNewPhotoUri.toString(), ivCardUp);
                        ivCardUp2.setVisibility(View.GONE);
                        bitmap = BitmapUtil.decodeBitmapFromFile(CameraUtil.getRealPathFromUri(mContext, mNewPhotoUri), 316, 200);
                        isUp = true;
                    } else if (type == 2) {
                        AvatarHelper.getInstance().displayUrl(mNewPhotoUri.toString(), ivCardDown);
                        ivCardDown2.setVisibility(View.GONE);
                        isDown = true;
                    }
                } else {
                    ToastUtil.showToast(this, R.string.c_crop_failed);
                }
            }
        }
    }

    private void commitImage() {
        Map<String, Object> map = new HashMap<>();
        map.put("key", AppConfig.AUTH_USER_KEY);
        map.put("image", BitmapUtil.Bitmap2StrByBase64(bitmap));
        map.put("side", "front");
        HttpUtils.post(AppConfig.AUTH_USER, map, new HttpUtils.HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = JSON.parseObject(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (jsonObject.getInteger("error_code") == 0) {
                            AuthUserInfo authUserInfo = JsonTool.jsonToObject(jsonObject.getString("result"), AuthUserInfo.class);
                            if (TextUtils.isEmpty(authUserInfo.getIdcard())) {
                                ToastUtil.showToast(AuthUserInfoActivity.this, "身份证信息有误，请上传正确的身份证照片");
                            } else {
                                pushAuthUserInfo(authUserInfo);
                            }
                        } else {
                            if (jsonObject.containsKey("reason"))
                                ToastUtil.showToast(AuthUserInfoActivity.this, jsonObject.getString("reason"));
                            else ToastUtil.showToast(AuthUserInfoActivity.this, "身份证信息读取错误，请重试");
                        }
                    }
                });

            }

            @Override
            public void onFail(String error) {
                Log.i("qin", error);
            }
        });
    }

    private void pushAuthUserInfo(AuthUserInfo authUserInfo) {
        String sex = "";
        if (authUserInfo.getSex().equals("男")) {
            sex = "1";
        } else {
            sex = "0";
        }
        Map<String, String> map = new HashMap<>();
        map.put("address", authUserInfo.getAddress());
        map.put("born", authUserInfo.getBorn());
        map.put("idcard", authUserInfo.getIdcard());
        map.put("nation", authUserInfo.getNation());
        map.put("realname", authUserInfo.getRealname());
        map.put("reason", "2");
        map.put("sex", sex);
        map.put("userId", getUser().getUserId());
        com.xuan.xuanhttplibrary.okhttp.HttpUtils.get()
                .url(AppConfig.AUTH_USER_INFO)
                .params(map)
                .build()
                .execute(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        JSONObject jsonObject = JSON.parseObject(result);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (jsonObject.getInteger("resultCode") == 1) {
                                    ToastUtil.showToast(AuthUserInfoActivity.this, "实名成功");
                                    setResult(2021);
                                    finish();
                                } else {
                                    if (TextUtils.isEmpty(jsonObject.getString("resultMsg")))
                                        ToastUtil.showToast(AuthUserInfoActivity.this, jsonObject.getString("resultMsg"));
                                    else
                                        ToastUtil.showToast(AuthUserInfoActivity.this, "实名失败");
                                }
                            }
                        });

                    }
                });
    }

}
